package com.ogawa.base.utils;

import androidx.annotation.NonNull;

import java.math.BigInteger;

public class HexUtil {

    /**
     * 二进制转16进制
     *
     * @param b
     * @param offset
     * @param count
     * @param haveSpace
     * @return
     */
    public static String getHexString(byte[] b, int offset, int count, boolean haveSpace) {
        String string = "";
        for (int i = offset; i < offset + count; i++) {
            String hex = Integer.toHexString(b[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            if (haveSpace)
                hex += " ";
            string = string + hex.toUpperCase();
        }
        return string;
    }

    /**
     * 高低位计算转换int值
     *
     * @param high
     * @param low
     * @return
     */
    public static int HIGH_LOW_TO_INT(byte high, byte low) {
        int data;
        data = (int) (high << 8) & 0x0000ff00;
        data |= (int) (low) & 0x000000ff;
        return data;
    }

    /**
     * 16 进制转2进制
     *
     * @param hexString
     * @return
     */
    public static byte[] hexStringToBytes(String hexString) {
        if (null == hexString || hexString.equals("")) {
            return null;
        }
        hexString = hexString.toUpperCase();
        int length = hexString.length() / 2;
        char[] hexChars = hexString.toCharArray();
        byte[] d = new byte[length];
        for (int i = 0; i < length; i++) {
            int pos = i * 2;
            d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
        }
        return d;
    }

    // 获取一个字节的8个bit======

    /**
     * @param b //     * @param start 从0开始-----对应的是高位
     *          //     * @param end   从7结束-----对应的是低位
     * @return
     */
    public static String getBitString(byte b, int[] count) {
        byte[] array = new byte[8];
        String newString = "";
        for (int i = 7; i >= 0; i--) {
            array[i] = (byte) (b & 1);
            b = (byte) (b >> 1);
        }
        // 其他位置清零
        for (int k = 0; k < count.length; k++) {
            array[count[k]] = 0;
        }
        // 拼接字符串
        for (int j = 0; j < array.length; j++) {
            newString = newString + array[j];
        }
        return newString;
    }

    /**
     * 二进制转字符串数据
     *
     * @param b
     * @return
     */
    public static String getBinaryString(byte[] b) {
        String data = null;
        for (byte K : b) {
            data = data + K;
        }
        return data;
    }

    /**
     * 16进制转2进制字符串
     *
     * @param hexString
     * @return
     */
    public static String hexString2binaryString(String hexString) {
        if (null == hexString || hexString.length() % 2 != 0) {
            return null;
        }
        String bString = "", tmp;
        for (int i = 0; i < hexString.length(); i++) {
            tmp = "0000" + Integer.toBinaryString(Integer.parseInt(hexString.substring(i, i + 1), 16));
            bString += tmp.substring(tmp.length() - 4);
        }
        return bString;
    }

    private static byte charToByte(char c) {
        return (byte) "0123456789ABCDEF".indexOf(c);
    }

    /**
     * 16进制加法计算
     *
     * @param hex
     * @return
     */
    public static String addHexString(String hex) {
        String[] hexs = new String[hex.length() / 2];
        for (int i = 0; i < hex.length() / 2; i++) {
            hexs[i] = hex.substring(i * 2, i * 2 + 2);
        }
        long total = 0;
        for (int i = 0; i < hexs.length; i++) {
            long getLong = Long.parseLong(hexs[i], 16);
            total = getLong + total;
        }
        String hexString = Long.toHexString(total);
        return hexString;
    }

    /**
     * 16进制转ASCII
     *
     * @param hex
     * @return
     */
    public static String convertHexToString(String hex) {
        StringBuilder sb = new StringBuilder();
        StringBuilder temp = new StringBuilder();
        // 49204c6f7665204a617661 split into two characters 49, 20, 4c...
        for (int i = 0; i < hex.length() - 1; i += 2) {
            String output = hex.substring(i, (i + 2));// grab the hex in pairs
            int decimal = Integer.parseInt(output, 16);// convert hex to decimal
            sb.append((char) decimal);// convert the decimal to character
            temp.append(decimal);
        }
        return sb.toString();
    }


    //7B0123 AB CB BC NM M      ..... 23

    /**
     * 16進制轉10進制
     *
     * @param hex
     * @return
     */
    public static int[] hexStringToAlgorism(String hex) {
        hex = hex.toUpperCase();
        int length = hex.length() / 2;
        int[] datas = new int[length];
        for (int i = 0; i < length; i++) {
            String hex1 = hex.substring(i * 2, i * 2 + 2);
            int max = hex1.length();
            int result = 0;
            for (int j = max; j > 0; j--) {
                char c = hex1.charAt(j - 1);
                int algorism = 0;
                if (c >= '0' && c <= '9') {
                    algorism = c - '0';
                } else {
                    algorism = c - 55;
                }
                result += Math.pow(16, max - j) * algorism;
            }
            datas[i] = result;
        }
        return datas;
    }

    /**
     * 16 进制转 10 进制（数字）
     *
     * @param str
     * @return
     */
    public static int hexToInt(String str) {
        int heightBit = Integer.parseInt(str.substring(0, 1), 16);
        int lowBit = Integer.parseInt(str.substring(1, 2), 16);
        return heightBit * 16 + lowBit;
    }

    /**
     * 10进制转16进制
     *
     * @param a
     * @param byteCount
     * @return
     */
    public static String algorismToHex(int a, int byteCount) {
        String hex = Integer.toHexString(a);
        if (hex.length() == byteCount * 2) {
            //
        } else if (hex.length() < byteCount * 2) {
            hex = toReturn0(byteCount * 2 - hex.length()) + hex;
        } else {
            hex = hex.substring(hex.length() - byteCount * 2, hex.length());
        }
        return hex.toUpperCase();
    }

    // // 10进制转16进制
    public static String intToHex(int a) {
        int byteCount = 1;
        String hex = Integer.toHexString(a);
        if (hex.length() == byteCount * 2) {
            //
        } else if (hex.length() < byteCount * 2) {
            hex = toReturn0(byteCount * 2 - hex.length()) + hex;
        } else {
            hex = hex.substring(hex.length() - byteCount * 2, hex.length());
        }
        return hex.toUpperCase();

    }

    /**
     * 返回0的个数
     *
     * @param i
     * @return
     */
    public static String toReturn0(int i) {
        String str = "";
        for (int j = 0; j < i; j++) {
            str = str + "0";
        }
        return str;
    }

    /**
     * 普通字符串转化为16进制的字符串
     * 比如：
     * WiFi名称：OGAWA-Guest  （转16进制）-> 4f474157412d4775657374
     * WiFi密码：ogawa888     （转16进制）-> 6f67617761383838
     *
     * @param str
     * @return
     */
    public static String strHexStr(String str) {
        return new BigInteger(1, str.getBytes()).toString(16);
    }

    /**
     * 将8位bit字节数组转换为16进制
     *
     * @param bits
     * @return
     */
    public static String bitToHex(@NonNull byte[] bits) {
        if (bits.length != 8) {
            return "";
        }
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < bits.length; i++) {
            builder.append(bits[i]);
        }
        int data = Integer.valueOf(builder.toString(), 2);
        return intToHex(data);
    }
}
